package com.cym.utils;

import java.io.File;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;

@Component
public class DownloadUtils {

	@Value("${spring.web.resources.static-locations[1]}")
	public String mp4;
	@Value("${spring.web.resources.static-locations[2]}")
	public String img;


	// 下载图片
	public void downloadImg() {
		List<File> files = FileUtil.loopFiles(mp4);

		for (File file : files) {
			if (!file.getName().endsWith("mp4") && !file.getName().endsWith("wmv") && !file.getName().endsWith("mkv") && !file.getName().endsWith("avi")) {
				continue;
			}

			try {
				String[] names = file.getName().split("\\.")[0].split("-");

				String code = names[0] + "-" + names[1].replace("a", "").replace("b", "");

				if (FileUtil.exist(img + code + ".jpg")) {
					continue;
				}

				String url = "https://javdb.com/search?q=" + code;
				System.out.println(url);
				String html = HttpRequest.get(url).setProxy(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 7897))).execute().body();
				Document doc = Jsoup.parse(html);

				Elements elements = doc.getElementsByClass("cover");

				if (elements.size() > 0) {
					String imgUrl = elements.get(0).getElementsByAttribute("src").get(0).attr("src");
					System.out.println(imgUrl);
					HttpUtil.downloadFile(imgUrl, img + code + ".jpg");
				}

				Thread.sleep(10 * 1000);

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}
}
